package com.fc.mall.kdniao.service.impl;

import com.fc.mall.kdniao.constants.KDNiaoConstants;
import com.fc.mall.kdniao.domain.LogisticTraceReq;
import com.fc.mall.kdniao.domain.LogisticTraceResp;
import com.fc.mall.kdniao.exception.KDNiaoErrorCode;
import com.fc.mall.kdniao.exception.KDNiaoException;
import com.fc.mall.kdniao.properties.KDNiaoProperties;
import com.fc.mall.kdniao.service.KDNiaoService;
import com.fc.mall.kdniao.util.EncryptUtils;
import com.fc.mall.kdniao.util.KDNiaoHttpClientUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.codec.Charsets;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class KDNiaoServiceImpl implements KDNiaoService {

    @Autowired
    private KDNiaoProperties kdNiaoProperties;

    @Override
    public LogisticTraceResp trackLogistic(LogisticTraceReq req) {
        Gson gson = new GsonBuilder().create();
        String requestData = gson.toJson(req);
        String param;
        try {
            param = generatePostStr(requestData, KDNiaoConstants.LOGISTIC_TRACK_REQUEST_TYPE);
        } catch (Exception ex) {
            throw new KDNiaoException(KDNiaoErrorCode.SERVICE_ERROR, ex.getMessage());
        }
        String responseBody = KDNiaoHttpClientUtils.getInstance().sendPost(kdNiaoProperties.getTrackLogisticUrl(),
                param, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
        LogisticTraceResp resp = gson.fromJson(responseBody, LogisticTraceResp.class);

        Collections.reverse(resp.getTraces());
        return resp;
    }

    /**
     * 生成请求字符串
     * @param requestData
     * @param requestType
     * @return
     * @throws Exception
     */
    private String generatePostStr(String requestData, String requestType) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("RequestData", URLEncoder.encode(requestData, Charsets.UTF_8.toString()));
        params.put("EBusinessID", kdNiaoProperties.geteBusinessId());
        params.put("RequestType", requestType);
        String dataSign = EncryptUtils.encrypt(requestData, kdNiaoProperties.getAppKey(), Charsets.UTF_8.toString());
        params.put("DataSign", URLEncoder.encode(dataSign, Charsets.UTF_8.toString()));
        params.put("DataType", "2");

        StringBuilder param = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if(param.length()>0){
                param.append("&");
            }
            param.append(entry.getKey());
            param.append("=");
            param.append(entry.getValue());
        }
        return param.toString();
    }
}
